package cn.xzq.crm.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.xzq.crm.dao.CustomerDao;
import cn.xzq.crm.entity.Customer;
import cn.xzq.crm.entity.PageBean;
import cn.xzq.crm.execption.CustomerException;

@Service("customerService")
@Transactional //开启事务
public class CustomerService {
	
	@Resource(name="customerDaoImpl")
	private CustomerDao customerDao;
	
	/**
	 * 添加客户
	 * @param customer
	 */
	public void add(Customer customer) {
		customerDao.add(customer);
	}

	/**
	 * 查找所有客户
	 * @return
	 */
	public List<Customer> findAll() {
		return customerDao.findAll();
	}
	
	/**
	 * 根据id删除一个客户
	 * @param custId
	 * @throws CustomerException
	 */
	public void delete(String custId) throws CustomerException {
		//根据id查找客户，删除客户
		Customer customer = customerDao.findOneById(custId);
		if(customer == null){
			throw new CustomerException("没有这个客户，删除失败！");
		}
		customerDao.delete(customer);
	}
	
	/**
	 * 根据id查找一个客户
	 * @param custId
	 */
	public Customer findOneById(String custId) {
		return customerDao.findOneById(custId);
	}
	
	/**
	 * 更新用户信息
	 * @param custId
	 */
	public void update(Customer customer) {
		customerDao.update(customer);	
	}
	
	/**
	 * 封装分页数据到pagebean
	 * @param currentPage
	 * @return
	 */
	public PageBean listPage(Integer currentPage, Integer pageSize) {
		//查询所有数据，放到pagebean中
		PageBean<Customer> pageBean = new PageBean<Customer>();
				//总记录数
		int pageCount = customerDao.findAllCount();
		pageBean.setTotalCount(pageCount); 
		//每页的记录数
		//int pageSize = 10;
		pageBean.setPageSize(pageSize);
		//总页数
		int totalPage = pageCount/pageSize;
		totalPage = (pageCount % pageSize == 0) ? totalPage : totalPage + 1;
		pageBean.setTotalPage(totalPage);
		//当前页
		if(currentPage <= 0){
			currentPage = 1;
		}else if(currentPage > totalPage){
			currentPage = totalPage;
		}
		pageBean.setCurrentPage(currentPage); 
		//开始位置
		int begin = (currentPage - 1) * pageSize;
		pageBean.setBegin(begin);
		//分页的数据
		List<Customer> alist = customerDao.findbyPageBean(begin, pageSize);
		pageBean.setList(alist);
		
		return pageBean;
	}

	/**
	 * 条件查询
	 * @param customer
	 */
	public List<Customer> findCondition(Customer customer) {
		return customerDao.findAllByCondition(customer);
	}
	
	/**
	 * 多条件组合查询
	 * @param customer
	 * @return
	 */
	public List<Customer> findMoreCondition(Customer customer) {
		return customerDao.findMoreCondition(customer);
	}
	
	
	
} 
